import { Button, Card, Form, Input, message, Popconfirm, Space } from "antd";
import {
  SearchOutlined,
  DeleteOutlined,
  EditOutlined,
} from "@ant-design/icons";
import React, { useCallback, useEffect, useState } from "react";
import Table, { ColumnsType } from "antd/lib/table";
import {
  ReqBatchRemoveHospital,
  ReqGetHospitalSet,
  ReqRemoveHospital,
} from "@/api/hospital/hospitalSet";
import { HospitalSetItem } from "@/api/hospital/model/hospitalSetTypes";
import { useNavigate } from "react-router-dom";

export default function HospitalSet() {
  // 声明数据总量的状态
  let [total, setTotal] = useState(0);
  // 声明当前页的状态
  let [current, setCurrent] = useState(1);
  // 声明每页显示数量的状态
  let [pageSize, setPageSize] = useState(5);
  // 声明一个渲染页面的状态
  let [hospitalSet, setHospitalSet] = useState<HospitalSetItem[]>([]);
  // 声明一个加载的状态
  let [loading, setLoading] = useState(false);
  // 声明一个params参数的状态
  let [params, setParams] = useState({ hosname: "", hoscode: "" });
  // 声明一个选中多选框的状态
  let [selectorKeys, setSelectorKeys] = useState<number[]>([]);
  // 创建一个form对象
  let [form] = Form.useForm();
  // 声明一个表单完成的函数
  let finish = () => {
    // 获取表单数据
    let fields = form.getFieldsValue();
    // 得到表单数据之后更新params参数
    setParams(fields);
    // 设置显示页面为1
    setCurrent(1);
  };
  let navigate = useNavigate();
  // 添加按钮的跳转
  let goToAddHospital = () => {
    navigate("/syt/hospital/hospitalset/add");
  };

  // 声明一个函数发送请求
  // useCallback是用来缓存一个函数,当函数发生变化时,用新函数更新缓存的函数
  let getHospitalSet = useCallback(async () => {
    setLoading(true);
    /**
     * page:当前显示页
     * limit:每页显示数据数量
     */
    let result = await ReqGetHospitalSet({
      page: current,
      limit: pageSize,
      ...params,
    });
    // 根据响应结果更新状态,动态渲染表格
    setHospitalSet(result.records);
    // 根据响应结果更新状态,更新数据的总量
    setTotal(result.total);
    setLoading(false);
  }, [current, pageSize, params]); //当current和pageSize发生变化时,内部函数会更新
  // 删除功能实现
  let remove = (id: string) => {
    return async () => {
      await ReqRemoveHospital(id);
      getHospitalSet();
    };
  };
  // 批量删除功能实现
  let batchRemove = async () => {
    await ReqBatchRemoveHospital(selectorKeys as number[]);
    message.success('批量删除成功');
    getHospitalSet();
  };
  useEffect(() => {
    // 页面挂载时发送ajax请求
    getHospitalSet();
  }, [getHospitalSet]); //当getHospital更新时,重新发送请求
  // 声明表格结构
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      fixed: "right",
      render: (value) => {
        return (
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => {
                navigate(`/syt/hospital/hospitalset/update/${value.id}`);
              }}
            ></Button>
            <Popconfirm
              title="请确定是否删除?"
              onConfirm={remove(value.id)}
              okText="Yes"
              cancelText="No"
            >
              <Button type="primary" danger icon={<DeleteOutlined />}></Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  return (
    <Card>
      {/* 搜索框 */}
      <Form layout="inline" onFinish={finish} form={form}>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button>清空</Button>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 按钮部分 */}
      <Space size="middle">
        <Button type="primary" onClick={goToAddHospital}>
          添加
        </Button>
        <Button onClick={batchRemove} disabled={selectorKeys.length === 0}>
          批量删除
        </Button>
      </Space>
      <div className="h-20"></div>
      {/* 表格部分 */}
      <Table
        rowSelection={{
          type: "checkbox",
          onChange: (selectedRowKeys: React.Key[]) => {
            setSelectorKeys(selectedRowKeys as number[]);
          },
        }}
        // 给表格添加一个加载效果
        loading={loading}
        // 在组件中传入数据
        dataSource={hospitalSet}
        // 组件中传入表格结构
        columns={columns}
        // 使表格底部出现滚动条
        scroll={{ x: 1450 }}
        // 给每行元素添加key值
        rowKey="id"
        // 给表格添加边框
        bordered={true}
        // 设置分页相关的属性
        pagination={{
          total, //数据的总量
          current, //显示当前页
          pageSize, //每页显示的数量
          showQuickJumper: true, //去第几页
          showSizeChanger: true, //显示调整每页显示几条数据的组件
          pageSizeOptions: [2, 5, 10], //自定义每页显示的组件
          showTotal: (total, range) => {
            //显示总页数
            return `总共:${total}`;
          },
          onChange: (page: number, pageSize: number) => {
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      ></Table>
    </Card>
  );
}
